<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/2 0002
 * Time: 上午 10:16
 */
namespace app\common\exception;

use app\common\err\ApiErrDesc;
use app\http\response\ResponseJson;
use think\exception\Handle;
use think\facade\Env;
use think\facade\Log;

class ExceptionHandler extends Handle{
    use ResponseJson;
    public function render(\Exception $e){
        if($e instanceof ApiException){
            //如果是自定义的异常
            $code = $e->getCode();
            $msg = $e->getMessage();
        }else{
            if(config('app_debug')){
                return parent::render($e);
            }else{
                $code = ApiErrDesc::UNKNOW_ERR[0];
                $msg = ApiErrDesc::UNKNOW_ERR[1];
                $this->recordErrorLog($e);
            }
        }

        return $this->jsonData($code,$msg);
    }

    private function recordErrorLog(\Exception $e)
    {
        Log::init(
            [
                'type' => 'File',
                'path' => Env::get('runtime_path') . 'log/',
                'level' => ['error']
            ]);
        Log::record($e->getMessage(), 'error');
    }
}